package com.itheima.web.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.domain.db.Admin;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.Map;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获得token
        String token = request.getHeader("Authorization");
        if (StrUtil.isEmpty(token)) {
            response.setStatus(401);//抛出权限不足
        }

        //2.校验redis是否过期
        token = token.replace("Bearer ", "");
        Boolean flag = stringRedisTemplate.hasKey(ConstantUtil.ADMIN_TOKEN + token);
        if (!flag) {
            response.setStatus(401);//抛出权限不足
        }

        //3.解析token
        Map map = JwtUtil.parseToken(token);
        Admin admin = BeanUtil.mapToBean(map, Admin.class, true);
        if (admin == null) {
            response.setStatus(401);//抛出权限不足
        }

        //4.绑定线程数据
        AdminHolder.set(admin);
        //5.续期操作
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN + token, "1", Duration.ofMinutes(30));
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AdminHolder.remove();
    }
}
